﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LuaInterface;

namespace Framework
{
    public static class LuaMonoTools
    {
        /// <summary>
        /// 给go添加一个lua组件容器，如果有则直接返回
        /// </summary>
        /// <param name="gameObject">go</param>
        /// <param name="luaContainerDefine">lua组件容器的定义</param>
        /// <returns></returns>
        public static LuaTable GetLuaComContainer(GameObject gameObject, LuaTable luaContainerDefine)
        {
            if (null == gameObject)
            {
                Logger.LogError("LuaMonoTools.GetLuaComContainer, gameObject = null");
                return null;
            }
            if (gameObject.Equals(null))
            {
                Logger.LogError("LuaMonoTools.GetLuaComContainer, gameObject Equals null");
                return null;
            }
            if (null == luaContainerDefine)
            {
                Logger.LogError("LuaMonoTools.GetLuaComContainer, luaContainerDefine = null, gameObject = " + gameObject.name);
                return null;
            }
            LuaMonoBehaviour luaMono = gameObject.OnceAddComponent<LuaMonoBehaviour>();
            if(null == luaMono)
            {
                Logger.LogError("LuaMonoTools.GetLuaComContainer, luaMono = null, gameObject = " + gameObject.name);
                return null;
            }
            if(null != luaMono.LuaComContainer)
            {
                return luaMono.LuaComContainer;
            }
            LuaFunction newFunc = luaContainerDefine.GetLuaFunction("New");
            if(null == newFunc)
            {
                string containerClassName = luaContainerDefine.GetStringField("__cname");
                Logger.LogError("LuaMonoTools.AddLuaComContainer, gameObject = " + gameObject.name + " luaContainerDefine = " + containerClassName);
            }
            LuaTable luaContainer = newFunc.Invoke<LuaMonoBehaviour, LuaTable>(luaMono);
            luaMono.SetLuaComContainer(luaContainer);
            return luaContainer;
        }
        
        /// <summary>
        /// 查询go上面的lua组件容器
        /// 找不到则返回null
        /// </summary>
        /// <param name="gameObject"></param>
        /// <returns></returns>
        public static LuaTable FindLuaComContainer(GameObject gameObject)
        {
            LuaMonoBehaviour luaMono = gameObject.GetComponent<LuaMonoBehaviour>();
            
            if(null != luaMono && null != luaMono.LuaComContainer)
            {
                return luaMono.LuaComContainer;
            }
            return null;
        }
    }
}
